import grails.converters.*

class EventdataController {

    def authenticateService

    def geoService

    def gfpService

    def index = {redirect(action: list, params: params)}

    // the delete, save and update actions only accept POST requests
    def allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

    def list = {
        if (authenticateService.ifAllGranted("ROLE_ADMIN")) {
            if (params.id) {
                def device = Device.get(params.id)
                if (!params.max) params.max = 10
                return [eventdataList: Eventdata.findAllByDevice(device, params)]
            } else {
                if (!params.max) params.max = 10
                return [eventdataList: Eventdata.list(params)]
            }
        } else if (authenticateService.ifAllGranted("ROLE_USER")) {
            if (params.id) {
                def device = Device.get(params.id)
                if (device.devicegroup.id == authenticateService.userDomain().id) {
                    if (!params.max) params.max = 10
                    return [eventdataList: Eventdata.findAllByDevice(device, params)]
                } else {
                    flash.message = "Device not found with id ${params.id}"
                    redirect(controller: "device", action: "list")
                }
            } else {
                if (!params.max) params.max = 10
                def userid = authenticateService.userDomain().id
                def lists = Eventdata.findAll("from Eventdata as b where b.device.devicegroup.user.id = " + userid, params)
                return [eventdataList: lists]
            }
        } else {
        }
    }

    def show = {
        def eventdata = Eventdata.get(params.id)
        if (!eventdata) {
            flash.message = "Eventdata not found with id ${params.id}"
            redirect(action: list)
        }
        else {return [eventdata: eventdata]}
    }

    def delete = {
        def eventdata = Eventdata.get(params.id)
        if (eventdata) {
            eventdata.delete()
            flash.message = "Eventdata ${params.id} deleted"
            redirect(action: list)
        }
        else {
            flash.message = "Eventdata not found with id ${params.id}"
            redirect(action: list)
        }
    }

    def edit = {
        def eventdata = Eventdata.get(params.id)

        if (!eventdata) {
            flash.message = "Eventdata not found with id ${params.id}"
            redirect(action: list)
        }
        else {
            return [eventdata: eventdata]
        }
    }

    def update = {
        def eventdata = Eventdata.get(params.id)
        if (eventdata) {
            eventdata.properties = params
            if (!eventdata.hasErrors() && eventdata.save()) {
                flash.message = "Eventdata ${params.id} updated"
                redirect(action: show, id: eventdata.id)
            }
            else {
                render(view: 'edit', model: [eventdata: eventdata])
            }
        }
        else {
            flash.message = "Eventdata not found with id ${params.id}"
            redirect(action: edit, id: params.id)
        }
    }

    def sr = {
        println params
        def device = null

        if (params.imei /*&& params.sim*/) {
            def imei = params.imei
            //def sim = params.sim
            //device = Device.findBySimPhoneNumberandImeiNumber(sim, imei)
            device = Device.findByImeiNumber(imei)
        }

        if (!device) {
            response.sendError(200, 'device not found');
            return
        }

        //FIXME user check?
        //FIXME check parameter validity

        def latitude = Double.parseDouble(params.lat);
        def longitude = Double.parseDouble(params.lon)
        def speed = Double.parseDouble(params.sd)
        def speedunit = params.su
        def heading = Double.parseDouble(params.hd)
        def altitude = Double.parseDouble(params.alt)
        def gpsAge = Integer.parseInt(params.ga)
        def horzAccuracy = Integer.parseInt(params.hz)


        def timestamp = new Date(Long.parseLong(params.ts))

        def statusCode = Integer.parseInt(params.sc)
        def address = params.ad
        //FIXME end

        Eventdata ed = new Eventdata()
        ed.latitude = (latitude < 90 && latitude > -90) ? latitude : 0
        ed.longitude = (longitude < 180 && longitude > -180) ? longitude : 0

        //def tsu = device.devicegroup.speedUnits;
        SpeedUnit su = SpeedUnit.getInstance(speedunit)
        ed.speed = speed * su.rate * SpeedUnit.getInstance("mph").rateFrom
        ed.heading = heading
        ed.altitude = altitude
        ed.gpsAge = gpsAge
        ed.horzAccuracy = horzAccuracy
        ed.timestamp = timestamp
        ed.statusCode = statusCode
        ed.address = address

        ed.dateCreated = new Date()

        gfpService.markGfp(ed, device);

        if (!ed.hasErrors() && device.addToEventdatas(ed).save()) {
            render "ok"
        } else {
            println " error,  failed"
            //render ed as JSON
            response.sendError(200, 'creat fail');
        }
    }


    def create = {
        def eventdata = new Eventdata()
        eventdata.properties = params
        return ['eventdata': eventdata]
    }

    def save = {
        println params
        def ed = new Eventdata(params)
        if (!ed.hasErrors() && params.device.id) {
            def device = Device.get(params.device.id.toString())              
            gfpService.markGfp(ed, device);
            println "222222222222222"
            if (device.addToEventdatas(ed)) {
                ed.save();
                flash.message = "Eventdata ${ed.id} created"
                redirect(action: show, id: ed.id)
            } else {
                render(view: 'create', model: [eventdata: ed])
            }
        }
        else {
            render(view: 'create', model: [eventdata: ed])
        }
    }
}